/**
 * ...
 *
 */
(function ($) {
	$.fn.threeDCircle = function (conf) {
		var toRadian = Math.PI / 180;
		var toDegree = 180 / Math.PI;

		// Shortcut function to apply CSS transform to all browsers
		var transform = function (el, ts) {
			var t = 'rotateX(' + (ts.rotateX || 0) + ')' + 
					'rotateY(' + (ts.rotateY || 0) + ')' + 
					'rotateZ(' + (ts.rotateZ || 0) + ')' + 
					'translateX(' + (ts.translateX || 0) + ')' + 
					'translateY(' + (ts.translateY || 0) + ')' + 
					'translateZ(' + (ts.translateZ || 0) + ')';

			el.css({
				webkitTransform: t, 
				mozTransform: t, 
				oTransform: t, 
				msTransform: t, 
				transform: t
			});
		};

		// Be nice
		return this.each(function () {
			var mover		= $(this).addClass('jquery-3d-circle-stage').find('> *').eq(0).addClass('jquery-3d-circle-mover');
			var circle		= mover.find('> *').eq(0).addClass('jquery-3d-circle');
			var items		= circle.find('> *');
			var numItems	= items.length;
			var currItem	= 0;
			var currAngle	= 0;

			// Make everything equal height
			items.equalHeight();

			var itemWidth = items.eq(0).outerWidth();
			var itemHeight = items.eq(0).outerHeight();

			circle.css({
				width: itemWidth + 'px', 
				height: itemHeight + 'px'
			});

			// And move the "mover" down z
			var radie = (itemWidth * numItems) / Math.PI / 2;

			transform(mover, {translateZ: '-' + radie + 'px'});

			// Position all the items
			var increase = Math.ceil(360 / numItems);
			var angle = 0;

			items.each(function (i) {
				var item		= $(this).addClass('jquery-3d-circle-item');

				transform(item, {
					translateZ:	radie + 'px', 
					rotateY:	angle + 'deg'
				});

				angle += increase;
			});

			// Goes to a specific item
			var gotoItem = function (nextItem) {
				if (currItem < nextItem) {
					var diffRight	= nextItem - currItem;
					var diffLeft	= currItem + (numItems - nextItem);
				}
				else {
					var diffRight	= (numItems - currItem) + nextItem;
					var diffLeft	= currItem - nextItem;
				}

				if (diffLeft < diffRight) {
					currAngle -= diffLeft * increase;
				}
				else {
					currAngle += diffRight * increase;
				}

				currItem = nextItem;

				transform(circle, {rotateY: -currAngle + 'deg'});

				// Change selected links
				$('a').removeClass('jquery-3d-circle-selected');
				$('a[href="#' + items.eq(currItem).attr('id') + '"]').addClass('jquery-3d-circle-selected');
			};

			// Rotate when clicking the items
			items.click(function () {
				gotoItem(items.index(this));
			});

			// Rotate the wrapper when links pointing to certain sections within it are clicked
			$('a').live('click', function () {
				var id = $(this).attr('href');
				var clicked = items.filter(id);

				if (clicked.length) {
					gotoItem(items.index(clicked));
				}

				return false;
			});
		});
	};
})(jQuery);
